package http

import (
	"context"
	"fmt"
	"gitee.com/zhucheer/orange/app"
	"gitee.com/zhucheer/orange/cfg"
	"gitee.com/zhucheer/orange/middlewares/exception"
	"gitee.com/zhucheer/orange/middlewares/throttle"
	"gitee.com/zhucheer/orange/project/http/controller"
	"gitee.com/zhucheer/orange/project/http/middleware"
	"net/http"
	"time"
)

type Route struct {
}

func (s *Route) ServeMux() {
	commonGp := app.NewRouter("", exception.NewPanicReader())
	{
		commonGp.GET("/", func(ctx *app.Context) error {
			return ctx.ToJson(map[string]interface{}{"data": "orange framework"})
		})

		commonGp.ALL("/welcome", controller.Welcome)
		commonGp.ALL("/welcome2", controller.Welcome2)
		commonGp.ALL("/view", controller.ViewShow)
		commonGp.ALL("/csrfToken", controller.CsrfToken)
		commonGp.ALL("/test", controller.Test)
		commonGp.GET("/appDefer", controller.AppDefer)

		commonGp.ALL("/uploadForm", controller.UploadForm)
		commonGp.ALL("/upload", controller.Upload)
		commonGp.ALL("/getfile", controller.ShowFile)
		commonGp.ALL("/getimage", controller.ShowImage)

		commonGp.GET("/captcha", controller.Captcha)
		commonGp.GET("/captchaCode", controller.CaptchaCode)
		commonGp.GET("/verifyimg", controller.VerifyImg)

		commonGp.GET("/selectMysql", controller.SelectMySql)
		commonGp.GET("/selectRedis", controller.SelectRedis)
		commonGp.GET("/selectMongo", controller.SelectMongo)
	}

	rateGp := commonGp.GroupRouter("/rate", throttle.NewThrottle(5, time.Minute, false))
	{
		rateGp.ALL("/", controller.Welcome)
		rateGp.GET(`/welcome/*`, controller.Welcome2)
		rateGp.GET(`/welcome/:id`, controller.Welcome)
		rateGp.ALL("/welcome-do", controller.Welcome)
		rateGp.GET("/welcome2ww/hello", controller.Welcome)
		rateGp.GET("/welcome/:page/:size", controller.Welcome2)
	}

	authGp := commonGp.GroupRouter("/auth", middleware.NewAuth())
	{
		authGp.ALL("/info", controller.AuthCheck)
		loginGp := authGp.GroupRouter("/auth/login", middleware.NewLogin())
		{
			loginGp.ALL("/info", controller.AuthCheck)
		}

	}

	// 注入自定义http handler 不走框架中间件，直接调用
	app.NewHttpHandler("/custom", MyHandler{})

	authGp.ASSETS("/file", "./storage", app.DirDeny)
}

func (s *Route) JobDispatch() {
	app.JobRun("opp", func(ctx *context.Context) error {
		fmt.Println("hello opp")
		appName := cfg.Config.GetString("app.name")
		fmt.Println("==========>", appName)
		time.Sleep(1 * time.Second)
		app.AppDefer(func() {
			fmt.Println("out put==================")
		})

		return nil
	}, 5)
}

// Register 服务注册器, 可以对业务服务进行初始化调用
func (s *Route) Register() {
	fmt.Println("init server")

}

type MyHandler struct {
}

func (MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	w.Write([]byte("custom http handler"))
}
